import 'dart:async';
import 'package:flutter/material.dart';
import '../models/camera_models.dart';
import '../managers/multi_camera_manager.dart';

/// 多摄像头预览Widget
///
/// 这是一个高级封装的摄像头预览组件，自动处理多种实现方案的切换，
/// 提供统一的API和丰富的自定义选项。
class MultiCameraPreview extends StatefulWidget {
  /// 摄像头配置
  final CameraConfig cameraConfig;

  /// 预览配置
  final CameraPreviewConfig previewConfig;

  /// 实现方案优先级配置
  final CameraImplementationPriority? priority;

  /// 首选实现方案
  final CameraImplementationType? preferredImplementation;

  /// 摄像头准备就绪回调
  final VoidCallback? onCameraReady;

  /// 错误回调
  final Function(CameraError)? onError;

  /// 状态变化回调
  final Function(CameraStatus)? onStatusChanged;

  /// 实现方案切换回调
  final Function(CameraImplementationType, CameraImplementationType, String)?
      onImplementationSwitched;

  /// 是否显示状态指示器
  final bool showStatusIndicator;

  /// 是否显示实现方案指示器
  final bool showImplementationIndicator;

  /// 是否显示错误信息
  final bool showErrorMessage;

  /// 自定义加载Widget
  final Widget? loadingWidget;

  /// 自定义错误Widget
  final Widget Function(CameraError)? errorWidgetBuilder;

  /// 是否启用自动初始化
  final bool enableAutoInitialization;

  const MultiCameraPreview({
    super.key,
    required this.cameraConfig,
    required this.previewConfig,
    this.priority,
    this.preferredImplementation,
    this.onCameraReady,
    this.onError,
    this.onStatusChanged,
    this.onImplementationSwitched,
    this.showStatusIndicator = false,
    this.showImplementationIndicator = false,
    this.showErrorMessage = true,
    this.loadingWidget,
    this.errorWidgetBuilder,
    this.enableAutoInitialization = false,
  });

  @override
  State<MultiCameraPreview> createState() => _MultiCameraPreviewState();
}

class _MultiCameraPreviewState extends State<MultiCameraPreview> {
  final MultiCameraManager _manager = MultiCameraManager.instance;
  CameraStatus _status = CameraStatus.uninitialized;
  CameraError? _lastError;
  bool _isInitialized = false;

  // Stream subscriptions for proper cleanup
  late StreamSubscription<CameraStatus> _statusSubscription;
  late StreamSubscription<CameraError> _errorSubscription;
  late StreamSubscription<CameraEvent> _eventSubscription;

  @override
  void initState() {
    super.initState();
    _setupListeners();

    // 如果启用了自动初始化，则配置管理器的自动初始化
    // 但是不在这里调用，让示例应用来控制时机

    // 检查管理器状态，只有在未初始化时才进行初始化
    if (_manager.status == CameraStatus.uninitialized) {
      // 如果启用了自动初始化，则不手动初始化，让管理器自动处理
      if (!widget.enableAutoInitialization) {
        _initializeCamera();
      }
    } else {
      // 如果已经初始化，直接更新状态
      setState(() {
        _status = _manager.status;
        _isInitialized = _manager.status == CameraStatus.initialized;
      });
    }
  }

  @override
  void dispose() {
    // 取消所有stream订阅
    _statusSubscription.cancel();
    _errorSubscription.cancel();
    _eventSubscription.cancel();

    // 注意：这里不调用manager.dispose()，因为可能有其他地方在使用
    super.dispose();
  }

  /// 初始化摄像头
  Future<void> _initializeCamera() async {
    // 如果管理器已经初始化，检查配置是否匹配
    if (_manager.status == CameraStatus.initialized) {
      // 这里可以添加配置比较逻辑，如果配置相同就直接使用
      if (mounted) {
        setState(() {
          _isInitialized = true;
          _status = CameraStatus.initialized;
        });
        widget.onCameraReady?.call();
      }
      return;
    }

    try {
      await _manager.initialize(
        config: widget.cameraConfig,
        priority: widget.priority,
        preferredImplementation: widget.preferredImplementation,
        context: context,
      );
      if (mounted) {
        setState(() {
          _isInitialized = true;
        });
        widget.onCameraReady?.call();
      }
    } catch (e) {
      final error = e is CameraError
          ? e
          : CameraError(
              code: 'INITIALIZATION_ERROR',
              message: e.toString(),
            );

      // 预览初始化失败时，错误已经由管理器的自动降级机制处理
      // 这里只需要更新UI状态
      if (mounted) {
        setState(() {
          _lastError = error;
        });
        widget.onError?.call(error);
      }
    }
  }

  /// 设置监听器
  void _setupListeners() {
    // 监听状态变化
    _statusSubscription = _manager.statusStream.listen((status) {
      if (mounted) {
        setState(() {
          _status = status;
        });
        widget.onStatusChanged?.call(status);
      }
    });

    // 监听错误
    _errorSubscription = _manager.errorStream.listen((error) {
      if (mounted) {
        setState(() {
          _lastError = error;
        });
        widget.onError?.call(error);
      }
    });

    // 监听事件
    _eventSubscription = _manager.eventStream.listen((event) {
      if (mounted && event is CameraImplementationSwitchedEvent) {
        widget.onImplementationSwitched?.call(
          event.oldImplementation,
          event.newImplementation,
          event.reason,
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        // 主要预览内容
        _buildMainContent(),

        // 状态指示器
        if (widget.showStatusIndicator) _buildStatusIndicator(),

        // 实现方案指示器
        if (widget.showImplementationIndicator) _buildImplementationIndicator(),
      ],
    );
  }

  /// 构建主要内容
  Widget _buildMainContent() {
    // 如果有错误且显示错误信息
    if (_lastError != null && widget.showErrorMessage) {
      print('📛 显示错误Widget: ${_lastError!.message}');
      if (widget.errorWidgetBuilder != null) {
        return widget.errorWidgetBuilder!(_lastError!);
      }
      return _buildDefaultErrorWidget(_lastError!);
    }

    // 如果未初始化或正在初始化
    if (!_isInitialized || _status == CameraStatus.initializing) {
      return widget.loadingWidget ?? _buildDefaultLoadingWidget();
    }

    // 如果已初始化、正在拍照或session已暂停，显示预览
    if (_status == CameraStatus.initialized ||
        _status == CameraStatus.takingPicture ||
        _status == CameraStatus.sessionPaused) {
      return _manager.buildPreview(
        previewConfig: widget.previewConfig,
        onCameraReady: widget.onCameraReady,
        onError: widget.onError,
      );
    }

    // 其他状态
    return _buildDefaultLoadingWidget();
  }

  /// 构建默认加载Widget
  Widget _buildDefaultLoadingWidget() {
    return Container(
      color: Colors.black,
      child: const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(color: Colors.white),
            SizedBox(height: 16),
            Text(
              '正在初始化摄像头...',
              style: TextStyle(color: Colors.white),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建默认错误Widget
  Widget _buildDefaultErrorWidget(CameraError error) {
    return Container(
      color: Colors.black,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              color: Colors.red,
              size: 48,
            ),
            const SizedBox(height: 16),
            const Text(
              '摄像头错误',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              error.message,
              style: const TextStyle(color: Colors.white70),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                if (mounted) {
                  setState(() {
                    _lastError = null;
                    _isInitialized = false;
                  });
                  _initializeCamera();
                }
              },
              child: const Text('重试'),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建状态指示器
  Widget _buildStatusIndicator() {
    return Positioned(
      top: 16,
      left: 16,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(
          color: Colors.black54,
          borderRadius: BorderRadius.circular(4),
        ),
        child: Text(
          _getStatusText(_status),
          style: const TextStyle(
            color: Colors.white,
            fontSize: 12,
          ),
        ),
      ),
    );
  }

  /// 构建实现方案指示器
  Widget _buildImplementationIndicator() {
    final implementation = _manager.currentImplementation;
    if (implementation == null) return const SizedBox.shrink();

    return Positioned(
      top: 16,
      right: 16,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(
          color: Colors.black54,
          borderRadius: BorderRadius.circular(4),
        ),
        child: Text(
          _getImplementationText(implementation),
          style: const TextStyle(
            color: Colors.white,
            fontSize: 12,
          ),
        ),
      ),
    );
  }

  /// 获取状态文本
  String _getStatusText(CameraStatus status) {
    switch (status) {
      case CameraStatus.uninitialized:
        return '未初始化';
      case CameraStatus.initializing:
        return '初始化中';
      case CameraStatus.initialized:
        return '已就绪';
      case CameraStatus.takingPicture:
        return '拍照中';
      case CameraStatus.error:
        return '错误';
      case CameraStatus.disposed:
        return '已释放';
      case CameraStatus.sessionPaused:
        return '会话暂停';
    }
  }

  /// 获取实现方案文本
  String _getImplementationText(CameraImplementationType implementation) {
    switch (implementation) {
      case CameraImplementationType.flutterCamera:
        return 'Flutter Camera';
      case CameraImplementationType.native:
        return '原生实现';
    }
  }
}
